package com.sumainfor.pc.market.service;

import com.alibaba.fastjson.JSONArray;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.SysUserVo;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.RdHousingInfoMapper;
import com.sumainfor.pc.market.dao.RdPactMapper;
import com.sumainfor.pc.market.dao.RdTenantMapper;
import com.sumainfor.pc.market.feign.Zfeign.ZzuulFeign;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date 2018年11月7日
 * @Describe 工程部查询房源配置
 */
@Service
public class RdTenantService implements Serializable {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(RdTenantService.class);// 日志

    @Autowired
    private RdTenantMapper rdTenantMapper;
    @Autowired
    private RdHousingInfoMapper rdHousingInfoMapper;
    @Autowired
    private ZzuulFeign zzuulFeign;
    @Autowired
    private RdPactMapper rdPactMapper;
    /**
     * 分页查询客户池
     */
    public List<Map<String,Object>>  getTenantList(Map<String,Object> parsms){

        return rdTenantMapper.getTenantList(parsms);
    }
    /**
     * 查询客户池的总数
     */
    public Integer getTenantListCount(Map<String,Object> params){
        return rdTenantMapper.getTenantListCount(params);
    }

    /**
     *签约时根据手机号查询是否有租客存在如果有就修改租客的信息，如果没有就新增租客
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer saveOrUpdateTenant(Map<String,Object> params){
        Integer result=0;
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                Map<String,Object> tDataMap=(Map<String,Object>)params.get("tData");//获取客户的数据
                //根据手机号查询是否有租客存在
                Integer countTenant=rdTenantMapper.getTenantForPactByTenMode(tDataMap);
                if (countTenant>0){//如果已经存在就去修改租客的信息
                    tDataMap.put("by", ContextUtils.getUserId());//操作人
                    tDataMap.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                    tDataMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonUpdateParms(tDataMap);
                    result=rdTenantMapper.updateTenantForPact(tDataMap);
                }else{//如果没有存在就去新增一条记录
                    tDataMap.put("by", ContextUtils.getUserId());//操作人
                    tDataMap.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                    tDataMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(tDataMap);
                    result=rdTenantMapper.addTenantForPact(tDataMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 创建客户的时候现根据手机查询是否已经有租客存在
     */
    public JsonResult getTenantByTenMode(Map<String,Object> params){
        JsonResult result=new JsonResult();
        params.put("SetId",ContextUtils.getUserId());
        if (params.get("SetId")==null){
            result.putFailed("参数不正确");
        }
        Map<String,Object> map=rdTenantMapper.getTenantByTenMode(params);
        if (map!=null){
            result.put(map);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }
    /**
     * 租后主管发起投诉时根据用户手机号查询到的用户的合同、房屋信息
     */
    public JsonResult getTenantInfoByTenMode(Map<String,Object> params){
        JsonResult result=new JsonResult();
        if (params.get("TenMode")==null){
            return result.putFailed("参数不正确");
        }
        List<Map<String,Object>> list=rdTenantMapper.getTenantInfoByTenMode(params);
        List<String> houIdList=new ArrayList<String>();  //房源详表编号的数组
        List<String> houInfoIdList=new ArrayList<String>();
        List<String> houInfoPubIdList=new ArrayList<String>();
        for (Map<String,Object> map: list){
            System.out.println("ProOperaType:"+map.get("ProOperaType"));
            if (map.get("ProOperaType")!=null && map.get("ProOperaType").toString().equals("2")){
                if(map.get("HouId")!=null){
                    houIdList.add(map.get("HouId").toString());
                }
            }else if(map.get("ProOperaType")!=null && map.get("ProOperaType").toString().equals("1")){
                houInfoIdList.add(map.get("HouInfoId").toString());
                houInfoPubIdList.add(map.get("HouId").toString());
            }
        }
        params.put("houIdList",houIdList);
        params.put("houInfoIdList",houInfoIdList);
        params.put("houInfoPubIdList",houInfoPubIdList);
        //查询房源的房间列表
        List<Map<String,Object>> houConList=rdPactMapper.getRdTemInteHouConInfoList(params);
        for (Map<String,Object> map1 :list){
            if (map1.get("HouId")!=null){
                for (Map<String,Object> map2 :houConList){
                    if (map2.get("HouId")!=null) {
                        if (map1.get("HouId").toString().equals(map2.get("HouId").toString())) {
                            map2.putAll(map1);
                        }
                    }
                }
            }
        }
        if (houConList!=null){
            result.put(houConList);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }
    /**
     * 租后主管投诉列表查询租客的信息和房源归属管家
     */
    public List<Map<String,Object>> getTenSysUserInfoListForGmio(Map<String,Object> params){
        //拿到租客编号
        List<Map<String,Object>> list=(List<Map<String, Object>>) params.get("tenBillList");
        System.out.println("list:"+list);
        Map<String,Object> map=new HashMap<String,Object>();
        List<Map<String,Object>> sysUserList=rdHousingInfoMapper.getSysUserIdListForGmio(params);
        System.out.println("sysUserList:"+sysUserList);
        map.put("sysUserList",sysUserList);//归属管家的集合

        JsonResult result=zzuulFeign.getSysUserBySysUserId(map);
        System.out.println("result:"+result);
        if (result.get("errorCode").equals("0")){
            Map<String,Object> zuulMap=(Map<String,Object>)result.get("result");
            List<Map<String,Object>> sList=(List<Map<String,Object>>)zuulMap.get("sysUserList");
            //遍历循环把服务管家的姓名放到集合中
            for (Map<String, Object> mmap : sysUserList) {
                if(mmap.get("SysUserId")!=null) {
                    for (Map<String, Object> zmap : sList) {
                        if (zmap.get("user_id")!=null){
                            if (MapUtils.getString(mmap, "SysUserId").equals(MapUtils.getString(zmap, "user_id"))) {
                                mmap.putAll(zmap);
                            }
                        }

                    }
                }
            }
        }
        for (Map<String, Object> mmap : list) {
            if(mmap.get("HouInfoId")!=null) {
                for (Map<String, Object> zmap : sysUserList) {
                    if (zmap.get("HouInfoId")!=null){
                        if (MapUtils.getString(mmap, "HouInfoId").equals(MapUtils.getString(zmap, "HouInfoId"))) {
                            mmap.putAll(zmap);
                        }
                    }

                }
            }
        }
        map.put("TenantList",list);//租客的集合
        List<Map<String,Object>> tList=rdTenantMapper.getTenantBySysTenId(map);
        System.out.println("tListtListtListtList:"+tList);
        //遍历循环把租客的姓名放到集合中
        for (Map<String, Object> mmap : list) {
            if(mmap.get("TenId")!=null) {
                for (Map<String, Object> zmap : tList) {
                    if(zmap.get("TenId")!=null) {
                        if (MapUtils.getString(mmap, "TenId").equals(MapUtils.getString(zmap, "TenId"))) {
                            mmap.putAll(zmap);
                        }
                    }
                }
            }
        }
        System.out.println("返回给运营部的数据:"+list);
        return  list;
    }
    /**
     *租后主管维修跟踪查询租客的信息
     */
    public List<Map<String,Object>> getTenUserList(Map<String,Object> params){
        return rdTenantMapper.getTenUserList(params);
    }
    /*
      维修师傅查询租客报修人的信息
     */
    public List<Map<String,Object>> getTenantListByTenId(Map<String,Object> params){
        return rdTenantMapper.getTenantListByTenId(params);
    }
    /**
     * 运营部服务管家查询已签约的租客列表
     */
    public List<Map<String,Object>> getTenantListForGmio(Map<String,Object> params){
        return rdTenantMapper.getTenantListForGmio(params);
    }
    /**
     * 运营部服务管家查询已签约的租客总数
     */
    public Integer getTenantListForGmioCount(Map<String,Object> params){
        return rdTenantMapper.getTenantListForGmioCount(params);
    }
    /**
     * 客户池点击已联系
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateTenantTime(Map<String,Object> params){
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                if (params.get("TenId")==null){
                    return result.putFailed("参数不正确");
                }
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                params.put("ContactTime",params.get("instm"));//客户的联系时间
                Integer count=rdTenantMapper.updateTenant(params);
                if (count>0){
                    result.putSuccess("操作成功");
                }else{
                    result.putFailed("服务器繁忙");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }

}
